import { ConfigProvider } from "antd";
import { HashRouter, Route } from "react-router-dom";
import zhCN from "antd/locale/zh_CN";
import RouterWrap from "./components/RouterWrap";
import Router from "./components/Router";
import { Helmet } from "react-helmet";
import { ComponentType, ReactElement } from "react";
import { OriginalRouteItem } from "./hooks/useRoute";
import NotFound from "./layout/NotFound/NotFound";

const App = () => {
    return (
        <>
            <Helmet>
                <title>{process.env.REACT_APP_TITLE}</title>
            </Helmet>
            <ConfigProvider locale={zhCN}>
                <HashRouter>
                    {/* RotuerWrap：确保请求拦截等操作设置完毕才会渲染子元素 */}
                    <RouterWrap>
                        {/* Router：自动导入组件等路由配置 */}
                        <Router />
                    </RouterWrap>
                </HashRouter>
            </ConfigProvider>
        </>
    );
};

export default App;

// 自动化导入页面，供路由配置使用
// 页面路径格式要求：在layout/views文件夹内
const components: Record<string, ComponentType> = {};
// contextList不能循环生成，webpack识别不到
const contextList = [
    { context: require.context("@/views", true, /\.tsx/), root: "views" },
    { context: require.context("@/layout", true, /\.tsx/), root: "layout" },
];
contextList.forEach(({ context, root }) => {
    context.keys().forEach(key => {
        const path = key.replace(/(\.\/|\.tsx)/g, "");
        const pathArr = path.split("/");
        if (pathArr.length === 2) components[`@/${root}/${path}`] = context(key).default;
    });
});

export const renderRoutes = (list: OriginalRouteItem[] = []): (ReactElement | null)[] => {
    return list.map(item => {
        const Element = item.component;
        if (!Element) {
            if (item.children) return renderRoutes(item.children);
            return null;
        }
        const getElement = () => {
            if (typeof Element === "string") {
                const Page = components[Element];
                if (!Page) return <NotFound/>;
                return <Page />;
            }
            return <Element />;
        };
        return (
            <Route key={item.path} path={item.path} element={getElement()}>
                {renderRoutes(item.children)}
            </Route>
        );
    }) as (ReactElement | null)[];
};
